package com.simtop.car.controller;


import com.github.pagehelper.PageInfo;
import com.simtop.car.common.ServerResponse;
import com.simtop.car.pojo.*;
import com.simtop.car.service.SourceService;
import com.simtop.car.utils.JwtUtil;
import com.simtop.car.utils.RedisUtil;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/source")
@CrossOrigin //todo 跨域问题
public class SourceController {

    private Logger logger= LoggerFactory.getLogger(SourceController.class);

    @Autowired
    public SourceService sourceService;

//    @Autowired
//    private RedisTemplate<String,String> redisTemplate;


    @Autowired
    public  RedisUtil redisUtil;


    /**
     * 获取资源来源（微博、微信、新闻......）
     * @param request
     * @return
     */
    @GetMapping(value = "/getSource")
    @ResponseBody
    public ServerResponse<List<Source>> getSource(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        List<Source> sourceList=sourceService.getSource();
        return ServerResponse.createBySuccess(sourceList);
    }


    /**
     * 字段映射
     * @return
     */
    @GetMapping(value = "/getFieldMapping")
    @ResponseBody
    public ServerResponse<List<FieldMapping>> getFieldMapping(Integer sourceId,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        logger.info("sourceId"+sourceId);
        List<FieldMapping> sourceList=sourceService.getFieldMapping(sourceId);
        return ServerResponse.createBySuccess(sourceList);
    }

    /**
     * 资源来源的数据
     * @param pageNum
     * @param pageSize
     * @param sourceId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getCarTypeSource", method = RequestMethod.GET)
    public ServerResponse<PageInfo> getCarTypeSource(HttpServletRequest request,Integer pageNum, Integer pageSize, Integer sourceId,Date date,Date nowDate,String[] brandType) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        if (StringUtils.isEmpty(pageNum)) {
            pageNum = 1;
        }
        return sourceService.getCarTypeSource(pageNum, pageSize, sourceId,date,brandType,u,nowDate);
    }

    /**
     * 根据数据编号来获取到数所数据的总数和
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAllSourceCount",method = RequestMethod.POST)
    public ServerResponse getAllSourceCount(HttpServletRequest request,@RequestBody SourceCount sourceCount){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        return sourceService.getAllSourceCount(sourceCount);
    }

    /**
     * 数据整合
     */
    @ResponseBody
    @RequestMapping(value = "/dataIntegration",method = RequestMethod.POST)
    public ServerResponse<ConformityDataResult>  dataIntegration(@RequestBody ConformityDataListResult conformityDataListResult,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
//        User u=new User();
//        u.setId(2);
       List<ConformityDataUtil> conformityDataUtilList=conformityDataListResult.getConformityDataUtilList();
       String[] brandType=conformityDataListResult.getBrandType().split(",");
        return sourceService.dataIntegration(conformityDataUtilList,brandType,u);
    }

    /**
     * 整合数据筛选
     * @param request
     * @param brandType
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/filterConsolidatedData",method = RequestMethod.POST)
    public ServerResponse<List<ConformityData>>  filterConsolidatedData(HttpServletRequest request,@RequestBody String brandType){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");






        }
        JSONObject jsonObject=new JSONObject(brandType);
        Integer pageNum=jsonObject.getInt("pageNum");
        Integer pageSize=jsonObject.getInt("pageSize");
        String source=jsonObject.getString("source");
        String brandTypeName=jsonObject.getString("brandType");
        if(StringUtils.isEmpty(pageNum)){
            pageNum=1;
        }
        List<ConformityData> conformityMappingList =(List<ConformityData>) redisUtil.lGetIndex("conformityData"+u.getId(),0);
        List<ConformityData> resultConformityData=conformityMappingList.stream().filter(item->brandTypeName.equals(item.getCarProduct())).collect(Collectors.toList());
        List<ConformityData> returnConformityData=resultConformityData.stream().filter(item->source.equals(item.getSource())).collect(Collectors.toList());
        return ServerResponse.createBySuccess(returnConformityData);
    }
    /**
     * 刷新删除数据
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteSelfInfo",method = RequestMethod.POST)
    public ServerResponse deleteSelfInfo(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        return sourceService.deleteSelfInfo(u);
    }

    /**
     * 获取发布的最新时间
     * @param request
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/dataReleaseDate",method = RequestMethod.POST)
    public ServerResponse dataReleaseDate(HttpServletRequest request,@RequestBody String object){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
       JSONObject jsonObject=new JSONObject(object);
        String[] sourceId=jsonObject.getString("sourceId").split(",");
        String[] brandType=jsonObject.getString("brandType").split(",");
        return sourceService.dataReleaseDate(sourceId,brandType);
    }



//    @ResponseBody
//    @RequestMapping(value = "/dataReleaseDate2",method = RequestMethod.POST)
//    public ServerResponse dataReleaseDate2(HttpServletRequest request,@RequestBody String object){
////        String token = request.getHeader("Authorization");
////        String jwt = token.substring(token.lastIndexOf(" ")+1);
////        User u = JwtUtil.unsign(jwt,User.class);
////        if(u == null){
////            return ServerResponse.createByErrorMsg("token无效");
////        }
//        JSONObject jsonObject=new JSONObject(object);
////        Integer sourceId=jsonObject.getInt("sourceId");
//        String[] sourceId=jsonObject.getString("sourceId").split(",");
//        String[] brandType=jsonObject.getString("brandType").split(",");
//        return sourceService.dataReleaseDate2(sourceId,brandType);
//    }

    /**
     * 图标展现工商信息
     * @param carProduct
     * @param request
     */
    @RequestMapping(value = "/getDisplayDataBusinessInformation",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<List<BusinessInformation>> getDisplayData(@RequestBody String carProduct,HttpServletRequest request){
        JSONObject jsonObject=new JSONObject(carProduct);
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        String[] brandType=jsonObject.getString("brandType").split(",");
        List<BusinessInformation> businessInformationList=sourceService.getDisplayDataBusinessInformation(brandType,u.getId());
        return  ServerResponse.createBySuccess(businessInformationList);
    }

    /**
     * 图标展现汽车品牌的信息（年份）
     * @param carProduct
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getDisplayDataNews",method = RequestMethod.POST)
    public ServerResponse<DisplayDataNews> getDisplayDataNews(@RequestBody String carProduct,HttpServletRequest request){
        JSONObject jsonObject=new JSONObject(carProduct);
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        String[] brandType=jsonObject.getString("brandType").split(",");
        Integer type=jsonObject.getInt("type");
        DisplayDataNews displayDataNews=sourceService.getDisplayDataNews(brandType,u.getId(),type);
        return ServerResponse.createBySuccess(displayDataNews);
    }


    /**
     * 获取专利信息、产品、数据
     * @param carProduct
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getDisplayDataPatent",method = RequestMethod.POST)
    public ServerResponse<DisplayDataNews> getDisplayDataPatent(@RequestBody String carProduct,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject=new JSONObject(carProduct);
        String[] brandType=jsonObject.getString("brandType").split(",");
        String data=jsonObject.getString("data");
        return sourceService.getDisplayDataPatent(brandType,data,u.getId());
    }

    /**
     * 获取数据总量
     * @param carProduct
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getTotalData",method = RequestMethod.POST)
    public ServerResponse<TotalData> getTotalData(@RequestBody String carProduct,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject=new JSONObject(carProduct);
        String[] brandType=jsonObject.getString("brandType").split(",");
        return sourceService.getTotalData(brandType,u.getId());
    }

    @ResponseBody
    @RequestMapping(value = "/getPatentClassificationNo",method = RequestMethod.POST)
    public ServerResponse<List<PatentClassificationNoUtil>> getPatentClassificationNo(@RequestBody String carProduct,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject=new JSONObject(carProduct);
        String[] brandType=jsonObject.getString("brandType").split(",");
        return sourceService.getPatentClassificationNo(brandType,u.getId());
    }


    /**
     * 根据来源获取来源的字段
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSourceField",method = RequestMethod.POST)
    public ServerResponse<List<FieldMappingResult>> getSourceField(HttpServletRequest request,@RequestBody String sourceField){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject=new JSONObject(sourceField);
        String array= jsonObject.getString("sourceId");
        if(StringUtils.isEmpty(array)){
            List<FieldMappingResult> fieldMappingResultList=new ArrayList<>();
            return ServerResponse.createBySuccess(fieldMappingResultList);
        }
        String sourceId[]=array.split(",");
        Integer sourceId2[]=new Integer[sourceId.length];
        for (int i = 0; i < sourceId.length; i++) {
            sourceId2[i]=Integer.parseInt(sourceId[i]);
        }
        return sourceService.getSourceField(sourceId2);
    }


    @ResponseBody
    @RequestMapping(value = "/getArray",method = RequestMethod.POST)
    public ServerResponse getArray(@RequestBody String sourceField){
        JSONObject jsonObject=new JSONObject(sourceField);
        String array= jsonObject.getString("sourceId");
        String sourceId[]=array.split(",");
        Integer sourceId2[]=new Integer[sourceId.length];
        for (int i = 0; i < sourceId.length; i++) {
            sourceId2[i]=Integer.parseInt(sourceId[i]);
        }
        return ServerResponse.createBySuccess(sourceId2);
    }


    /**
     * 根据汽车品牌和来源数据信息来做词频统计
     * @param conformityDataListResult
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/sourceWordFrequency",method = RequestMethod.POST)
    public ServerResponse<List> sourceWordFrequency(@RequestBody ConformityDataListResult conformityDataListResult,HttpServletRequest request) throws IOException {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        return sourceService.sourceWordFrequency(conformityDataListResult);
    }

    /**
     *确认整合数据
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/commitConformityData",method =RequestMethod.POST)
    public ServerResponse commitConformityData(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        return  sourceService.commitConformityData(u);
    }



}
